//  公共的方法
let platForm = uni.getSystemInfoSync().uniPlatform;
let device = uni.getSystemInfoSync().platform;
let baseUrl;
let debugUrl = "https://ihuoniao.cn"; // 请求地址,https://ihuoniao.cn;http://zjl.215000.com; 本地线上地址切换这个
let time = parseInt(+new Date() / 1000);
let needParam = {
	platform_version: '1.0',
	platform_timestamp: time,
	platform_name: '',
};
//平台切换
if (platForm == 'mp-toutiao') { //抖音
	baseUrl = (uni.getExtConfigSync && uni.getExtConfigSync()['extConfig']['masterDomain']) ? uni
		.getExtConfigSync()['extConfig']['masterDomain'] : debugUrl; //请求域名
	needParam.platform_name = "dy_miniprogram"
} else if (platForm == 'web') { //H5
	baseUrl = process.env.NODE_ENV == 'development' ? '' : (window.masterDomains || debugUrl) //生产环境和开发环境域名不一样，且要打开代理
	needParam.platform_name = "h5"
} else if (platForm == 'mp-weixin') { //微信
	baseUrl = (uni.getExtConfigSync && uni.getExtConfigSync()['masterDomain']) ? uni
		.getExtConfigSync()['masterDomain'] : debugUrl; //请求域名
	needParam.platform_name = "wx_miniprogram"
}
let arr = Object.entries(needParam);
for (let i = 0; i < arr.length; i++) {
	let item = arr[i].join('=');
	arr[i] = item;
}
let needParamString = arr.join('&');

/**
 * 请求获取token,接口返回用户信息获取失败
 * 1.可能因为token过期，2.也有可能是被挤下线 token失效，3.也有可能是token已刷新 但是之前获取的是旧的
 * **/ 
// 全局工具函数
let app = getApp();
const $ajax = {
	get: function({ //get方法
		url,
		data = {},
		state = false
	}) {
		
		return new Promise(function(resolve, reject) {
			if (typeof data == 'string') {
				data = `${data}&${needParamString}`
			} else if (typeof data == 'object') {
				data = {
					...data,
					...needParam
				};
			} else {
				reject('请求数据格式错误');
			}
			uni.request({
				url: `${baseUrl}/${url}`,
				data: data,
				method: "GET",
				success: function(res) {
					app = getApp()
					if (res.statusCode !== 200) {
						reject(res);
					} else {
						let token_expired = uni.getStorageSync('token_expired');
						let nowtime = Date.parse(new Date()) / 1000;
						if(res.data.state != 100 && res.data.info == '用户信息验证失败' ){ 
							if(nowtime < token_expired){
								//可能被挤掉线
								uni.removeStorageSync('access_token');
								uni.removeStorageSync('refresh_token');
								uni.removeStorageSync('userid');
								uni.removeStorageSync('token_expired');
								if(app){

									app.globalData.access_token = null;
									app.globalData.refresh_token = null;
									app.globalData.token_expired = null;
									app.globalData.userid = null;
								}
							}
						}else{
							resolve(res);
						}

					}
				},
				fail: function(err) {

					reject(err);
				}
			})
		})
	},
	post: function({
		url,
		data = {},
		header = 'application/x-www-form-urlencoded;charset=UTF-8'
	}) {

		return new Promise(function(resolve, reject) {
			let param;
			if (typeof data == 'string') {
				param = `${data}&${needParamString}`
			} else if (typeof data == 'object') {
				param = {
					...data,
					...needParam
				};
			} else {
				reject('请求数据格式错误');
			}
			// console.log(`地址链接：${url};携带数据：${param}`);
			uni.request({
				url: `${baseUrl}/${url}`,
				data: param,
				method: "POST",
				header: {
					'Content-Type': header
				},
				success: function(res) {
					if (url.includes('byteMiniProgramConnect') && res.data.state != 100 &&
						res.data.info == '格式错误！') {
						uni.showModal({
							title: '接口错误',
							content: `参数:${JSON.stringify(param)}`
						})
					}
					if (res.statusCode !== 200) {
						reject(res);
					} else {
						app = getApp()
						let token_expired = uni.getStorageSync('token_expired');
						let nowtime = Date.parse(new Date()) / 1000;
						if(res.data.state != 100 && res.data.info == '用户信息验证失败' && nowtime < token_expired){ 
							//可能被挤掉线
							uni.removeStorageSync('access_token');
							uni.removeStorageSync('refresh_token');
							uni.removeStorageSync('userid');
							uni.removeStorageSync('token_expired');
							if(app){
								app.globalData.access_token = null;
								app.globalData.refresh_token = null;
								app.globalData.token_expired = null;
								app.globalData.userid = null;
							}
						}
						resolve(res);
					}
				},
				fail: function(err) {
					reject(err)
				}
			})
		})
	},
	upMedia: function({ //上传图片和视频
		seFile = true, //选择图片上传开启/关闭(必填)
		type = 'image', //'image'是图片，其他默认是视频(必填)
		formData, //必填
		path, //上传路径（seFile=false时必填）
		upConfig = {}, //上传参数（可选）
		needLoad = false, //上传时是否出现loading(可选，传函数)
	}) {
		return new Promise(function(resolve, reject) {
			if (seFile) { //选择上传
				if (type == 'image') { //图片（支持多张）
					uni.chooseImage({
						...upConfig,
						success: res => {
							if (!needLoad) {
								uni.showLoading({
									title: '上传中'
								});
							} else {
								needLoad();
							}
							path = res.tempFilePaths;
							async function moreUp(path) { //多张上传
								let arr = [];
								for (let i = 0; i < path.length; i++) {
									arr[i] = await $ajax.upFile(path[i], formData);
								};
								return arr;
							};
							moreUp(path).then(res => {
								uni.hideLoading();
								resolve(res);
							});
						},
						fail: err => {
							reject(err);
						}
					});
				} else { //视频
					uni.chooseVideo({
						...upConfig,
						success: res => {
							if (!needLoad) {
								uni.showLoading({
									title: '上传中'
								});
							} else {
								needLoad();
							}
							path = res.tempFilePath;
							$ajax.upFile(path, formData).then(res => {
								uni.hideLoading();
								resolve(res);
							});
						},
						fail: err => {
							reject(err);
						}
					});
				}
			} else {
				$ajax.upFile(path, formData).then(res => {
					uni.hideLoading();
					resolve(res);
				});
			};
		})
	},
	upFile: function(path, formData) { //上传文件
		return new Promise(function(resolve, reject) {
			uni.uploadFile({
				name: 'Filedata',
				filePath: path,
				url: baseUrl + '/include/upload.inc.php',
				formData: formData,
				success: res => {
					resolve(res);
				},
				fail: err => {
					reject(err);
				}
			})
		})
	}
}
export default $ajax;